package com.example.musicplayer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    //声明一个MediaPlayer
    private MediaPlayer mediaPlayer;
    //声明一个计时器
    private Timer timer;

    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
    }

    //添加计时器用于设置音乐播放器中的播放进度条
    public void addTimer() {
        if (timer == null) {
            timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (mediaPlayer == null) {
                        return;
                    }
                    int duration = mediaPlayer.getDuration();//获取歌曲总时长
                    int currentPosition = mediaPlayer.getCurrentPosition();//获取播放进度
                    Message message = MusicActivity.handler.obtainMessage();
                    //将音乐的总时长和播放进度封装至bundle中
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);
                    //再将Bundle封装至Message消息对象中
                    message.setData(bundle);
                    //最后将消息发送到主线程的消息队列
                    MusicActivity.handler.sendMessage(message);
                }
            };

            timer.schedule(timerTask, 5, 500);
        }
    }

    class MusicControl extends Binder {
        public void play(int i) {
            Uri uri = Uri.parse("android.resource://"+getPackageName()+"/raw/"+"music"+i);
            mediaPlayer.reset();
            mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
            mediaPlayer.start();
            addTimer();
        }

        /**
         * 暂停
         */
        public void pausePlay() {
            mediaPlayer.pause();
        }

        /**
         * 继续
         */
        public void continuePlay() {
            mediaPlayer.start();
        }

        /**
         * 设置音乐播放位置
         */
        public void seekTo(int progress) {
            mediaPlayer.seekTo(progress);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer == null) {
            return;
        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        mediaPlayer = null;
    }
}